package com.littlebee.storysuper.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.littlebee.storysuper.R;
import com.littlebee.storysuper.adapter.CircleAdapter;
import com.littlebee.storysuper.entry.CircleEntry;
import com.littlebee.storysuper.entry.EnglishEntry;
import com.littlebee.storysuper.entry.NewstVideoEntry;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.utils.DateUtils;
import com.littlebee.storysuper.utils.GsonUtils;
import com.littlebee.storysuper.utils.NetWorkUtils;
import com.littlebee.storysuper.utils.ToastUtil;
import com.littlebee.storysuper.utils.Utils;
import com.zss.library.activity.BaseActivity;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class PhotoActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private List<CircleEntry> mCircleBeans = new ArrayList<CircleEntry>();
    private ListView mListView;
    private CircleAdapter adapter;
    /**
     * 主页有可能用到下拉刷新
     */
    private SwipeRefreshLayout mSwipeLayout;
    private static final int REFRESH_COMPLETE = 0X110;
    JSONObject object;
    View hand;
    /**
     * 是否在播放
     */
    private boolean isPlaying;
    /**
     * 播放进度
     */
    private int currPost = 0;
    /**
     * 用于做延迟加载
     */
    private Handler handler = null;
    /**
     * 视频播放组件
     */
    private VideoView videoView;
    /**
     * 播放or暂停
     */
    private ImageView playPauseIv;
    /**
     * 播放进度
     */
    private TextView nowProgressTv;
    /**
     * 播放进度条
     */
    private SeekBar progressBar;
    /**
     * 总进度
     */
    private TextView totalLengthTv;
    private int diversityIndex = 0;

    /**
     * 播放以前的初始化图片
     */
    private ImageView videoInitIv;
    /**
     * 视频标题
     */
    private TextView videoTitleTv;
    NewstVideoEntry entry = null;
    private ImageView show_to_player;
    private ImageView more_iv;
    @Override
    public int getLayoutResId() {
        return R.layout.activity_photo;
    }

    @Override
    public void initView() {
        super.initView();
        mListView = (ListView) findViewById(R.id.listview);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);

        mSwipeLayout.setOnRefreshListener(this);
        handler = new Handler();
        hand = getLayoutInflater(R.layout.layout_englist_info_top);
        videoInitIv = (ImageView) hand.findViewById(R.id.init_video_iv);
        videoTitleTv = (TextView) hand.findViewById(R.id.video_title_tv);
        show_to_player= (ImageView) hand.findViewById(R.id.show_to_player);
        videoView = (VideoView) hand.findViewById(R.id.video_view);
        playPauseIv = (ImageView) hand.findViewById(R.id.play_pause_iv);
        nowProgressTv = (TextView) hand.findViewById(R.id.now_progress_tv);
        progressBar = (SeekBar) hand.findViewById(R.id.progressBar);
        totalLengthTv = (TextView) hand.findViewById(R.id.total_length_tv);
        playPauseIv.setOnClickListener(this);
        more_iv=(ImageView) hand.findViewById(R.id.more_iv);
        more_iv.setVisibility(View.VISIBLE);
        more_iv.setOnClickListener(this);

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        getInfo();

    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        toolbar.setTitle(getString(R.string.boby_photo_txt));
//        toolbar.setRightText("视频列表");
//        toolbar.setOnRightListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

    }

    /**
     * 获取图片
     */
    public void getInfo() {
        User user = Utils.getUserEntry();
        if (user != null) {
            HashMap<String, String> map = new HashMap<>();
            map.put("phoneId", user.getMobile());
//        map.put("password","123456");
            // TODO: 2017/8/15
            NetWorkUtils.post(PhotoActivity.this, "getbabyphotographinfo", map, true, new NetWorkUtils.IListener() {

                @Override
                public void onSuccess(String result, JSONObject resObj) {
                    object = resObj;
                    mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 0);


                }

                @Override
                public void onError(String result, String code, String msg) {
                    mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 0);

                }
            });
        }
    }

    @Override
    public void onRefresh() {
        getInfo();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case REFRESH_COMPLETE:
                    // TODO: 2017/8/15
                    mSwipeLayout.setRefreshing(false);
                    if (object != null) {
                        try {
                            String res1 = object.getJSONObject("response").optString("newstvideo");
                            mListView.removeHeaderView(hand);
                            if (res1.equals("{}")) {
                                entry = null;
                            } else {
                                entry = GsonUtils.getObjFromJSON(res1, NewstVideoEntry.class);
                                if (entry != null) {

                                    if (videoView != null && videoView.isPlaying()) {
                                        playPauseIv.setImageResource(R.mipmap.ransfer_media_play);
                                        currPost = videoView.getCurrentPosition();
                                        videoView.pause();
                                        isPlaying = false;
                                    }
                                    mListView.addHeaderView(hand);
                                    videoTitleTv.setText(entry.videostartday);
                                    Glide.with(PhotoActivity.this).load(entry.videominiphoto).error(R.mipmap.logo_img).into(videoInitIv);
                                    show_to_player.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Intent intent=new Intent(PhotoActivity.this,PlayerInfoActivity.class);
                                            intent.putExtra("url",entry.videourl);
                                            intent.putExtra("title",entry.videostartday);
                                            intent.putExtra("pos",0);
                                            intent.putExtra("pic",entry.videominiphoto);

                                            startActivity(intent);
                                        }
                                    });
                                }
                            }
                            String res = object.getJSONObject("response").optString("thisweekphotos");
                            LogUtils.i("XHX", "XHXSize11:" + res);
                            mCircleBeans = GsonUtils.getListFromJSON(res, CircleEntry.class);
                            Collections.reverse(mCircleBeans);
                            LogUtils.i("XHX", "XHXSize:" + mCircleBeans.size());

                            if (adapter == null) {
                                adapter = new CircleAdapter(mCircleBeans, PhotoActivity.this);
                                mListView.setAdapter(adapter);
                            } else {
                                adapter.notifyDataSetChanged();
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    break;

            }
        }

    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_pause_iv:
                if (videoView != null && videoView.isPlaying()) {
                    playPauseIv.setImageResource(R.mipmap.ransfer_media_play);
                    currPost = videoView.getCurrentPosition();
                    videoView.pause();
                    isPlaying = false;
                } else {
                    videoInitIv.setVisibility(View.GONE);
                    videoTitleTv.setVisibility(View.GONE);
                    playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);
                    play(entry.videourl, currPost);
                }
                break;
            case R.id.more_iv:
                Intent intent=new Intent(PhotoActivity.this,VideoListActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void initPlayer(int diversityIndex, int currPost) {
        videoInitIv.setVisibility(View.GONE);
        videoTitleTv.setVisibility(View.GONE);

        playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);

        videoTitleTv.setText(entry.videostartday);
        play(entry.videourl, currPost);
    }

    private SeekBar.OnSeekBarChangeListener change = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (videoView != null && videoView.isPlaying()) {
                // 设置当前播放的位置
                videoView.seekTo(progress);
                //修改时间
            }
        }
    };

    /**
     * 播放咯
     *
     * @param path 地址
     * @param msec 播放进度
     */
    protected void play(String path, int msec) throws NullPointerException {
        //获取视频文件地址

        videoView.setVideoURI(Uri.parse(path));
        LogUtils.i("XHX", "初始化播放器了");
        //开始播放
        videoView.start();

        // 按照初始位置播放
        videoView.seekTo(msec);

        //修改时间
        // 开始线程，更新进度条的刻度
        new Thread() {
            @Override
            public void run() {
                try {
                    isPlaying = true;
                    while (isPlaying) {
                        // 如果正在播放，没0.5.毫秒更新一次进度条
                        int current = videoView.getCurrentPosition();
                        progressBar.setMax(videoView.getDuration());
                        progressBar.setProgress(current);
                        handler.post(runnableUi);
                        sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // 在播放完毕被回调 续播还是结束播放
//                if (diversityIndex < names.size() - 1) {
//                    diversityIndex += 1;
//                    currPost = 0;
//                    videoTitleTv.setText(names.get(diversityIndex).getCartoonname());
//                    play(names.get(diversityIndex).getCartoonplayurl(), currPost);
//                } else {
                videoInitIv.setVisibility(View.VISIBLE);
                videoTitleTv.setVisibility(View.VISIBLE);
                ToastUtil.displayShortToast("播放结束");

                //}
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //TODO  发生错误重新播放
                play(entry.videourl, 0);
                isPlaying = false;
                return false;
            }
        });
    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面播放进度的文字标识
            if (videoView.getDuration() != -1) {
                totalLengthTv.setText(DateUtils.getTimeString(videoView.getDuration()));
            }
            nowProgressTv.setText(DateUtils.getTimeString(videoView.getCurrentPosition()));

        }

    };
}
